<?php

namespace common\service;
use common\model\TaskModel;
use support\SingletonTrait;

class TaskV2Service
{
    use SingletonTrait;

    /**
     * 获取与我相关的统计数量
     *  通过前端传过来的code+筛选条件筛选与我相关的数据
     * @param string $fields
     * @param string $responseFormatType
     * @param string $code 前端权限CODE【我创建的,我分配的,我负责的,我参与的】
     * @param array  $rangTime ["range_time":[开始时间,结束时间]]
     * @param array  $filter 筛选条件 【项目,集,环节工序,搜索....】
     * @param array  $page
     * @param int    $limit
     * @return array ["count":"数量，最多不超过100个"]
     */
    public function getTaskMember(string $fields, string $responseFormatType = 'count', string $code = '', array $rangTime = [0, 0], array $filter = [], array $page = [0, 100], $order = "", int $limit = 100): array
    {
        $returnData = [
            'count' => 0,
            'list' => [],
            'group_by_list' => []
        ];
        if (empty($fields)) {
            $fields = "distinct task.id";
        }
        $extendFilter['range_time'] = $rangTime;
        $taskMemberModel = model(TaskModel::class)
            ->field($fields)
            ->join('entity on entity.id = task.entity_id', 'LEFT')
            ->join('module on entity.module_id = module.id', 'LEFT')
            ->join('task_member on task_member.task_id = task.id', 'left');
        if (in_array($code, ['workOrderTask'])) {
            $taskMemberModel = $taskMemberModel->join('task_work_order on task_work_order.task_id = task_member.task_id', 'left');
        }

        $needTaskStepType = [
            TaskModel::STEP_TYPE_STEP,
            TaskModel::STEP_TYPE_STANDARD_REVIEW,
            TaskModel::STEP_TYPE_STANDARD_MEETING,
            TaskModel::STEP_TYPE_STANDARD_MAKE_TO_DO,
            TaskModel::STEP_TYPE_WORK_ORDER_TO_DO,
            TaskModel::STEP_TYPE_ENTITY_TO_DO,
            TaskModel::STEP_TYPE_TO_DO,
            TaskModel::STEP_TYPE_PERSON,
        ];
        $taskFilter = [
            'task.step_type' => ['in', $needTaskStepType],
            'task.tenant_id' => \request()->getTenantId(),
        ];
        $tempFilter = $this->getFilterByCode($code, $extendFilter);
        if (!empty($tempFilter)) {
            $taskFilter = [$tempFilter, $taskFilter];
        }
        if ($responseFormatType == 'count' && $limit > 0) {
            $taskMemberModel = $taskMemberModel->limit($limit);
        }
        if ($responseFormatType == 'list') {
            $taskMemberModel = $taskMemberModel->page(...$page);
        }
        // 集筛选
        if (!empty($filter['initial_episode_code_list'])) {
            $initialEpisodeCodeList = $filter['initial_episode_code_list'];
            $taskFilter[] = ['_string' => EntityService::getInstance()->initialEpisodeCodeSql($initialEpisodeCodeList, "initial_episode_code", "showings_number")];
        }
        // 任务状态
        if (!empty($filter['task_status'])) {
            $taskStatus = $filter['task_status'];
            $taskFilter[] = ['task.`json`->>"$.task_status"' => ['in', $taskStatus]];
        }
        // 任务名
        if (!empty($filter['task_name'])) {
            $taskName = $filter['task_name'];
            $taskFilter[] = ['_string' => "((task.name like '%$taskName%') or entity.name like '%$taskName%' or entity.code like '%$taskName%')"];
        }
        unset($filter['initial_episode_code_list']);
        unset($filter['task_status']);
        unset($filter['task_name']);
        if (!empty($filter)) {
            $taskFilter[] = $filter;
        }
        if (empty($order) && $responseFormatType == 'list') {
            $order = 'task.id desc';
        }
        if (!empty($order)) {
            $taskMemberModel = $taskMemberModel->order($order);
        }
        $result = $taskMemberModel
            ->where($taskFilter)
            ->select();
        if (empty($result)) {
            return $returnData;
        }
        if ($responseFormatType == 'count') {
            $returnData['count'] = count($result);
        }
        if ($responseFormatType == 'list') {
            $returnData['list'] = $result;
        }
        return $returnData;
    }


    /**
     * 通过code 找到对应 where 条件
     * @param string $code
     * @param        $extendFilter
     * @return mixed
     */
    public function getFilterByCode(string $code, $extendFilter)
    {
        $filter = [];
        if (empty($code)) {
            return $filter;
        }
        $finalStatusId = StatusService::getInstance()->byCode('final')['id'];
        $remakeStatusId = StatusService::getInstance()->byCode('remake')['id'];
        $closedStatusId = StatusService::getInstance()->byCode('closed')['id'];
        $feedbackStatusId = StatusService::getInstance()->byCode('feedback')['id'];
        $submittedStatusId = StatusService::getInstance()->byCode('submitted')['id'];
        $notStartedStatusId = StatusService::getInstance()->byCode('not_started')['id'];
        $waitForPartyAReviewStatusId = StatusService::getInstance()->byCode('wait_for_party_a_review')['id'];
        // 我创建的
        $userId = \request()->getUserId();
        $dayRange = get_current_day_range(time());
        if ($code == 'createdTask') {
            $rangeTime = $extendFilter['range_time'];
            if (!empty($rangeTime[0]) && !empty($rangeTime[1])) {
                $filter['task.created'] = ["between", $rangeTime];
            }
            $filter['task.created_by'] = $userId;
        }
        // 我分配的
        if ($code == 'assignedTask') {
            $filter['task.assignee_producer'] = $userId;
        }
        // 我负责的
        if ($code == 'responsibleTask') {
            $filter['task.assignee'] = $userId;
        }
        // 我参与的
        if ($code == 'participatedTask') {
            $filter['task_member.partner'] = $userId;
        }
        // 全部任务
        if ($code == 'allTask') {
            $filter['task_member.partner'] = $userId;
        }
        // 返修中任务
        if ($code == 'underRepairTask') {
            $filter['task_member.partner'] = $userId;
            $filter['task.`json`->>"$.task_status"'] = ['in', "$remakeStatusId,$feedbackStatusId"];
        }
        // 审核中任务
        if ($code == 'underReviewTask') {
            $filter['task_member.partner'] = $userId;
            $filter['task.`json`->>"$.task_status"'] = ['in', "$submittedStatusId,$waitForPartyAReviewStatusId"];
        }
        // 逾期任务
        if ($code == 'abnormalTask') {
            $filter['task_member.partner'] = $userId;
            $filter['task.`json`->>"$.task_status"'] = ['not in', "$closedStatusId,$finalStatusId"];
            $filter['task.plan_delivery_time'] = ['between', [1, $dayRange['sdate']]];
        }
        // 工单任务
        if ($code == 'workOrderTask') {
            $filter['task_member.partner'] = $userId;
            $filter['task_work_order.status'] = 0;
            $filter['task.`json`->>"$.task_status"'] = ['not in', "$finalStatusId"];
            $filter[] = [
                'task.plan_delivery_time' => ['lt', $dayRange['edate']],
                'task.plan_end_time' => ['lt', $dayRange['edate']],
                '_logic' => 'or',
            ];
        }
        // 今日应交付任务
        if ($code == 'dueToday') {
            $filter['task_member.partner'] = $userId;
            $filter['task.`json`->>"$.task_status"'] = ['not in', "$closedStatusId,$finalStatusId"];
            $filter['task.plan_delivery_time'] = ["between", array_values($dayRange)];
//                ->whereIn('task.step_type', ['step', 'standard_make_to_do'])
        }
        // 今日应完成任务
        if ($code == 'completedToday') {
            $filter['task_member.partner'] = $userId;
            $filter['task.`json`->>"$.task_status"'] = ['not in', "$closedStatusId,$finalStatusId"];
            $filter['task.plan_end_time'] = ["between", array_values($dayRange)];
//                ->whereIn('task.step_type', ['step', 'standard_make_to_do'])
        }
        // 生产任务
        if ($code == 'produceTask') {
            $filter['task_member.partner'] = $userId;
            $filter['task.step_type'] = ['in', 'step,standard_make_to_do'];
            $filter['task.`json`->>"$.task_status"'] = ['not in', "$closedStatusId,$finalStatusId"];
            $filter[] = [
                'task.plan_delivery_time' => ['lt', $dayRange['edate']],
                'task.plan_end_time' => ['lt', $dayRange['edate']],
                '_logic' => 'or',
            ];
        }
        // 标准会议
        if ($code == 'standardMeet') {
            $filter['task_member.partner'] = $userId;
            $filter['task.step_type'] = 'standard_meeting';
            $filter['task.`json`->>"$.task_status"'] = $notStartedStatusId;
        }
        // 标准审核
        if ($code == 'standardExamine') {
            $filter['task_member.partner'] = $userId;
            $filter['task.step_type'] = 'standard_review';
            $filter['task.`json`->>"$.task_status"'] = $notStartedStatusId;
        }
        // 个人待办
        if ($code == 'personalTodo') {
            $filter['task_member.partner'] = $userId;
            $filter['task.step_type'] = 'person';
            $filter['task.`json`->>"$.task_status"'] = $notStartedStatusId;
        }
        return $filter;
    }

}
